<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['checkmachinery:checkmachinery:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['checkmachinery:checkmachinery:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkmachineryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备编码" align="center" prop="machineryCode" />
      <el-table-column label="设备名称" align="center" prop="machineryName" />
      <el-table-column label="品牌" align="center" prop="machineryBrand" />
      <el-table-column label="规格型号" align="center" prop="machinerySpec" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['checkmachinery:checkmachinery:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['checkmachinery:checkmachinery:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改点检设备对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="checkmachineryRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="计划ID" prop="planId">
          <el-input v-model="form.planId" placeholder="请输入计划ID" :disabled="true" />
        </el-form-item>
        <el-form-item label="设备选择" prop="machineryId">
          <el-input 
            v-model="form.machineryName" 
            placeholder="请选择设备" 
            readonly
            @click="openDeviceSelectDialog"
          />
          <el-input v-model="form.machineryId" type="hidden" />
          <el-input v-model="form.machineryCode" type="hidden" />
        </el-form-item>
        <el-form-item label="设备编码" prop="machineryCode">
          <el-input v-model="form.machineryCode" placeholder="设备编码" readonly />
        </el-form-item>
        <el-form-item label="设备名称" prop="machineryName">
          <el-input v-model="form.machineryName" placeholder="设备名称" readonly />
        </el-form-item>
        <el-form-item label="品牌" prop="machineryBrand">
          <el-input v-model="form.machineryBrand" placeholder="请输入品牌" readonly/>
        </el-form-item>
        <el-form-item label="规格型号" prop="machinerySpec">
          <el-input v-model="form.machinerySpec" placeholder="请输入规格型号" readonly/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设备选择弹窗 -->
    <el-dialog title="选择设备" v-model="deviceSelectVisible" width="800px" append-to-body>
      <el-form :inline="true" :model="deviceQuery" class="mb-4">
        <el-form-item label="设备编码">
          <el-input v-model="deviceQuery.machineryCode" placeholder="请输入设备编码" clearable />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="deviceQuery.machineryName" placeholder="请输入设备名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchDevices">查询</el-button>
          <el-button @click="resetDeviceQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table 
        :data="deviceList" 
        border 
        @row-click="handleDeviceRowClick"
        @selection-change="handleDeviceSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="machineryCode" label="设备编码" />
        <el-table-column prop="machineryName" label="设备名称" />
        <el-table-column prop="machineryBrand" label="品牌" />
        <el-table-column prop="machinerySpec" label="规格型号" />
      </el-table>
      <el-pagination
        :total="deviceTotal"
        v-model:page="deviceQuery.pageNum"
        v-model:limit="deviceQuery.pageSize"
        @pagination="getDeviceList"
        style="margin-top: 10px;"
      />
      <template #footer>
        <el-button @click="deviceSelectVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDeviceSelection">确认选择</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Checkmachinery">
import { watch, onMounted, ref, reactive, toRefs } from 'vue'
import { listCheckmachinery, getCheckmachinery, delCheckmachinery, addCheckmachinery, updateCheckmachinery } from "@/api/checkmachinery/checkmachinery"
import { listMachinery } from "@/api/machinery/machinery"
const { proxy } = getCurrentInstance()

// 设备选择相关变量
const deviceSelectVisible = ref(false)
const deviceList = ref([])
const deviceTotal = ref(0)
const selectedDevice = ref(null)
const deviceQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  machineryCode: null,
  machineryName: null
})

// 主数据
const checkmachineryList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planId: null,
    machineryId: null,
    machineryCode: null,
    machineryName: null,
    machineryBrand: null,
    machinerySpec: null,
  },
  rules: {
    planId: [
      { required: true, message: "计划ID不能为空", trigger: "blur" }
    ],
    machineryId: [
      { required: true, message: "请选择设备", trigger: "blur" }
    ],
    machineryCode: [
      { required: true, message: "设备编码不能为空", trigger: "blur" }
    ],
    machineryName: [
      { required: true, message: "设备名称不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)
const isMounted = ref(false);

// 接收父组件传递的计划ID
const props = defineProps({
  currentPlanId: {
    type: [Number, String, null],
    default: null
  }
});

// 组件挂载时
onMounted(() => {
  isMounted.value = true;
  if (props.currentPlanId) {
    queryParams.value.planId = props.currentPlanId;
    getList();
  }
});

// 监听计划ID变化
watch(
  () => props.currentPlanId,
  (newVal) => {
    if (isMounted.value) {
      queryParams.value.planId = newVal;
      if (newVal) {
        getList();
      } else {
        checkmachineryList.value = [];
        total.value = 0;
      }
    }
  },
  { immediate: false }
);

/** 查询点检设备列表 */
function getList() {
  if (!queryParams.value.planId) {
    checkmachineryList.value = [];
    total.value = 0;
    loading.value = false;
    return;
  }
  loading.value = true
  listCheckmachinery(queryParams.value).then(response => {
    checkmachineryList.value = response.rows
    total.value = response.total
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 设备选择相关方法
function openDeviceSelectDialog() {
  deviceSelectVisible.value = true;
  deviceQuery.pageNum = 1;
  getDeviceList();
}

function getDeviceList() {
  listMachinery(deviceQuery).then(response => {
    deviceList.value = response.rows;
    deviceTotal.value = response.total;
  }).catch(() => {
    proxy.$modal.msgError("获取设备列表失败");
  })
}

function searchDevices() {
  deviceQuery.pageNum = 1;
  getDeviceList();
}

function resetDeviceQuery() {
  deviceQuery.machineryCode = null;
  deviceQuery.machineryName = null;
  deviceQuery.pageNum = 1;
  getDeviceList();
}

function handleDeviceRowClick(row) {
  selectedDevice.value = row;
}

function handleDeviceSelectionChange(selection) {
  if (selection.length > 0) {
    selectedDevice.value = selection[0];
  } else {
    selectedDevice.value = null;
  }
}

function confirmDeviceSelection() {
  if (!selectedDevice.value) {
    proxy.$modal.msgWarning("请选择设备");
    return;
  }
  
  // 选择设备后自动填充相关字段
  form.value.machineryId = selectedDevice.value.machineryId;
  form.value.machineryCode = selectedDevice.value.machineryCode;
  form.value.machineryName = selectedDevice.value.machineryName;
  form.value.machineryBrand = selectedDevice.value.machineryBrand || '';
  form.value.machinerySpec = selectedDevice.value.machinerySpec || '';
  
  deviceSelectVisible.value = false;
  selectedDevice.value = null;
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    planId: props.currentPlanId || null, // 重置时保留计划ID
    machineryId: null,
    machineryCode: null,
    machineryName: null,
    machineryBrand: null,
    machinerySpec: null,
    remark: null,
    attr1: null,
    attr2: null,
    attr3: null,
    attr4: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  if (proxy.$refs["checkmachineryRef"]) {
    proxy.resetForm("checkmachineryRef")
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  if (proxy.$refs["queryRef"]) {
    proxy.resetForm("queryRef")
  }
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 - 固定planId为父组件传递的值 */
function handleAdd() {
  reset()
  // 固定计划ID为父组件传递的currentPlanId
  form.value.planId = props.currentPlanId;
  open.value = true
  title.value = "添加点检设备"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _recordId = row.recordId || ids.value[0]
  getCheckmachinery(_recordId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改点检设备"
  }).catch(() => {
    proxy.$modal.msgError("获取设备信息失败")
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["checkmachineryRef"].validate(valid => {
    if (valid) {
      if (form.value.recordId != null) {
        updateCheckmachinery(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(() => {
          proxy.$modal.msgError("修改失败")
        })
      } else {
        // 确保新增时planId是父组件传递的值
        form.value.planId = props.currentPlanId;
        addCheckmachinery(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(() => {
          proxy.$modal.msgError("新增失败")
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _recordIds = row ? [row.recordId] : ids.value
  if (_recordIds.length === 0) {
    proxy.$modal.msgWarning("请选择要删除的记录")
    return
  }
  
  proxy.$modal.confirm(`是否确认删除选中的${_recordIds.length}条数据？`).then(function() {
    return delCheckmachinery(_recordIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('checkmachinery/checkmachinery/export', {
    ...queryParams.value
  }, `checkmachinery_${new Date().getTime()}.xlsx`)
}

// 初始加载列表
getList()
</script>
